﻿using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
using ZyGame.Resource;

namespace ZyGame.Transport
{
    public class DownloadContext
    {
        public string url;
        public string name;
        public byte[] bytes;
        private int retryCount;
        private uint version;
        private uint crc;
        public DownloadState state;
        public PackageInfo package;
        private UnityWebRequest request;
        private const int MAX_RETRY_COUNT = 5;

        public float progress => request is null ? 0 : request.downloadProgress;

        public DownloadContext(string url, uint version, uint crc)
        {
            this.url = url;
            name = Path.GetFileName(url);
            state = DownloadState.None;
            retryCount = 0;
            this.version = version;
            this.crc = crc;
        }

        internal DownloadContext(PackageInfo package) : this(AppConfig.GetHotfixAssetPath(package.name), package.version, package.crc)
        {
            this.package = package;
        }

        public IEnumerator Start()
        {
            state = DownloadState.Process;
            retryCount++;
            request = UnityWebRequest.Get(url);
            request.timeout = 60;
            request.useHttpContinue = true;
            yield return request.SendWebRequest();
            if (!request.isDone || request.result != UnityWebRequest.Result.Success)
            {
                Client.Console.WriteLine(request.error, url);
                state = DownloadState.Failure;
                if (retryCount < MAX_RETRY_COUNT)
                {
                    yield return new WaitForSeconds(1f);
                    yield return Start();
                }
                yield break;
            }

            bytes = new byte[request.downloadHandler.data.Length];
            Array.Copy(request.downloadHandler.data, 0, bytes, 0, request.downloadHandler.data.Length);
            Client.Console.WriteLine(request.url, request.downloadHandler.data.Length);
            Client.File.WriterData(name, bytes, version, crc);
            request.Dispose();
            state = DownloadState.Completed;
        }
    }
}